<?php
// 简单的API测试脚本

// 模拟会话
session_start();

// 如果是获取菜单的请求
if (isset($_GET['action']) && $_GET['action'] === 'menu') {
    // 数据库连接配置
    $host = '127.0.0.1';
    $dbname = 'oa5';
    $username = 'root';
    $password = '123456';

    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // 查询菜单数据
        $sql = "SELECT id, pid, title, icon, src, mig_src, sort, status 
                FROM oa_admin_rule 
                WHERE status = 1 AND menu = 1 
                ORDER BY sort ASC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $menuItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 构建菜单树
        $menuTree = buildMenuTree($menuItems);
        
        // 返回JSON格式数据
        header('Content-Type: application/json');
        echo json_encode([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'menu' => $menuTree,
                'admin' => [
                    'id' => 1,
                    'name' => '管理员',
                    'type' => 1
                ],
                'system' => [
                    'version' => '1.0.0',
                    'name' => '勾股OA'
                ],
                'web' => [
                    'title' => '勾股OA系统',
                    'description' => '现代化办公系统'
                ]
            ]
        ]);
        
    } catch(PDOException $e) {
        header('Content-Type: application/json');
        echo json_encode([
            'code' => 500,
            'msg' => '数据库错误: ' . $e->getMessage(),
            'data' => null
        ]);
    }
    exit;
}

/**
 * 构建菜单树结构
 */
function buildMenuTree($menuList, $parentId = 0) {
    $tree = [];

    foreach ($menuList as $menu) {
        if ($menu['pid'] == $parentId) {
            $children = buildMenuTree($menuList, $menu['id']);
            
            // 构建菜单项
            $menuItem = [
                'id' => (int)$menu['id'],
                'pid' => (int)$menu['pid'],
                'title' => $menu['title'],
                'icon' => $menu['icon'],
                'sort' => (int)$menu['sort'],
                'status' => (int)$menu['status'],
                'src' => $menu['src'], // 原始路径
                'mig_src' => $menu['mig_src'], // 迁移后的前端路由路径
                'path' => $menu['mig_src'] ?: $menu['src'] // 优先使用迁移后的路径
            ];

            // 如果有子菜单，添加到children字段
            if (!empty($children)) {
                $menuItem['children'] = $children;
            }

            $tree[] = $menuItem;
        }
    }

    // 按sort字段排序
    usort($tree, function($a, $b) {
        return $a['sort'] <=> $b['sort'];
    });

    return $tree;
}

// 显示测试页面
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>API测试</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <h1>API测试页面</h1>
    <button onclick="testMenuAPI()">测试菜单API</button>
    <div id="result" style="margin-top: 20px; white-space: pre-wrap;"></div>

    <script>
        function testMenuAPI() {
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = '正在请求API...';
            
            // 发送请求到API
            fetch('/test_api.php?action=menu')
                .then(response => response.json())
                .then(data => {
                    resultDiv.innerHTML = JSON.stringify(data, null, 2);
                })
                .catch(error => {
                    resultDiv.innerHTML = '请求失败: ' + error.message;
                });
        }
    </script>
</body>
</html>